<template>
  <el-button class="upload-btn" @click="openDialog(0)">add user</el-button>
  
  <div>
    <el-table :data="users" style="width: 100%">
      <!-- <el-table-column prop="id" label="id"></el-table-column> -->
      <el-table-column prop="username" label="userId" width="120"></el-table-column>
      <el-table-column prop="name" label="name" width="120"></el-table-column>
      <el-table-column
        prop="sex"
        label="sex"
         width="120"
        :formatter="sexFormatter"
      ></el-table-column>
      <el-table-column prop="email" label="email" width="120"></el-table-column>
      <el-table-column prop="regdate" label="registered date"
      width="180"
      :formatter="dateFormatter"></el-table-column>
      <el-table-column label="delete">
        <template v-slot="scope">
          <el-button
            type="danger"
            value="return"
            @click="disableUser(scope.row)"
            >delete</el-button
          >
        </template>
      </el-table-column>
    </el-table>
  </div>

  <user-dialog
    v-model:visible="dialogFormVisible"
    :mode="mode"
    :dialogData="dialogData"
    @upload="onUploaded"
  ></user-dialog>
</template>
<script lang="ts" setup>
import { onMounted, ref } from "vue";
import * as userApi from "@/api/user";
import type { User } from "@/domain/reader";
import { ElMessage } from "element-plus";

import UserDialog from "./UserListDialog.vue";
const dialogFormVisible = ref(false);
const mode = ref<0 | 1>(0);
const dialogData = ref();
const openDialog = (targetMode: 0 | 1, user?: any) => {
  mode.value = targetMode;
  dialogFormVisible.value = true;
  dialogData.value = user;
};
const onUploaded = () => {
  getUsers();
};

const users = ref<User[]>([]);

const getUsers = function () {
  userApi.getUsers({ curPage: 0, pageSize: 24 }).then((data) => {
    users.value = data;
  });
};
onMounted(() => {
  getUsers();
});

const sexFormatter = (row: any, col: any, value: number) => {
  return value === 1 ? "男" : "女";
};

const dateFormatter = (row: any, col: any, value: string | number | Date) => {
  return `${new Date(value).toLocaleDateString()} ${new Date(value).toLocaleTimeString()}`;
};

const disableUser = function (user: User) {
  userApi
    .disableUser({
      id: user.id,
    })
    .then(() => {
      ElMessage.success("delete5 successfully");
      getUsers();
    })
    .catch(err => {
      ElMessage.error(err);
    });
};
</script>

<style scoped>
.upload-btn {
  float: left;
}
</style>
